<template>
  <div class="accident-management">
    <div class="page-header">
      <h2>长者安全记录</h2>
      <p class="page-description">细心记录每一次关怀，守护长者平安健康</p>
    </div>

    <div class="filter-section">
      <el-row :gutter="20">
        <!-- 护工：显示老人选择 -->
        <el-col :span="6" v-if="role === 'caregiver'">
          <el-select v-model="selectedElder" placeholder="选择长者" clearable @change="load" class="filter-item">
            <el-option label="全部长者" value="all" />
            <el-option v-for="e in elders" :key="e.elderId" :label="e.name" :value="e.elderId" />
          </el-select>
        </el-col>

        <!-- 时间筛选 -->
        <el-col :span="6">
          <el-date-picker
            v-model="selectedDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="load"
            class="filter-item"
          />
        </el-col>

        <el-col :span="6">
          <el-button type="primary" @click="load" class="filter-item">查询记录</el-button>
        </el-col>

        <el-col :span="6" style="text-align: right;">
          <el-button type="success" @click="openAdd()" class="add-button">记录安全事件</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table :data="tableData" row-key="recordId" class="accident-table">
      <el-table-column prop="elderName" label="长者姓名" width="120" />
      <el-table-column prop="accidentDesc" label="事件描述" min-width="200">
        <template #default="{ row }">
          <div class="description-text">
            {{ row.accidentDesc }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="handleDesc" label="处理措施" min-width="200">
        <template #default="{ row }">
          <div class="description-text">
            {{ row.handleDesc }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="happenTime" label="发生时间" width="160" />
      <el-table-column prop="severity" label="严重程度" width="120">
        <template #default="{ row }">
          <el-tag :type="getSeverityTag(row.severity)" effect="light" class="severity-tag">
            {{ getSeverityText(row.severity) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">查看详情</el-button>
          <el-button 
            v-if="role !== 'caregiver'" 
            type="danger" 
            size="small" 
            @click="del(row.recordId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="show" :title="isAdd ? '记录安全事件' : '查看事件详情'">
      <el-form :model="form" label-width="100px">
        <el-form-item label="长者选择" v-if="role === 'caregiver'">
          <el-select v-model="form.elderId" placeholder="请选择长者">
            <el-option v-for="e in elders" :key="e.elderId" :label="e.name" :value="e.elderId" />
          </el-select>
        </el-form-item>
        <el-form-item label="长者ID" v-else>
          <el-input v-model="form.elderId" />
        </el-form-item>
        <el-form-item label="事件描述">
          <el-input type="textarea" v-model="form.accidentDesc" :rows="3" placeholder="请详细描述事件发生的情况..." />
        </el-form-item>
        <el-form-item label="处理措施">
          <el-input type="textarea" v-model="form.handleDesc" :rows="3" placeholder="请记录采取的处理措施和后续关怀..." />
        </el-form-item>
        <el-form-item label="严重程度">
          <el-select v-model="form.severity">
            <el-option label="轻微" value="MINOR" />
            <el-option label="一般" value="MODERATE" />
            <el-option label="严重" value="SEVERE" />
          </el-select>
        </el-form-item>
        <el-form-item label="发生时间">
          <el-date-picker
            v-model="form.happenTime"
            type="datetime"
            placeholder="选择日期和时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submit" v-if="isAdd">保存记录</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getAccidentsByElder, addAccident, updateAccident, deleteAccident, getAccidentsByCaregiver } from '@/api/accident'
import { getEldersByCaregiver } from '@/api/meal'
import axios from '@/api/axios'

const tableData = ref([])
const elders = ref([])
const selectedElder = ref('all')
const selectedDateRange = ref(null)
const show = ref(false)
const isAdd = ref(true)
const form = ref({})

const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
const role = userInfo.role

const load = async () => {
  try {
    let res
    if (role === 'caregiver') {
      // 护工默认显示所有负责老人的事故记录
      const params = {}
      if (selectedElder.value && selectedElder.value !== 'all') {
        params.elderId = selectedElder.value
      }
      if (selectedDateRange.value) {
        params.startDate = selectedDateRange.value[0]
        params.endDate = selectedDateRange.value[1]
      }
      res = await getAccidentsByCaregiver(userInfo.caregiverId, params)
    } else {
      // 其他角色按老人筛选
      if (!selectedElder.value) {
        tableData.value = []
        return
      }
      res = await getAccidentsByElder(selectedElder.value)
    }
    tableData.value = res.data
  } catch (e) {
    console.error('[Accident] load error', e)
    ElMessage.error('加载安全记录失败')
  }
}

// 获取严重程度标签样式
const getSeverityTag = (severity) => {
  const severityMap = {
    'MINOR': 'success',
    'MODERATE': 'warning',
    'SEVERE': 'danger'
  }
  return severityMap[severity] || 'info'
}

// 获取严重程度文本
const getSeverityText = (severity) => {
  const severityMap = {
    'MINOR': '轻微',
    'MODERATE': '一般',
    'SEVERE': '严重'
  }
  return severityMap[severity] || '未知'
}

const openAdd = () => {
  form.value = {
    caregiverId: userInfo.caregiverId,
    severity: 'MINOR',
    happenTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
  }
  isAdd.value = true
  show.value = true
}

const openEdit = (row) => {
  form.value = { ...row }
  isAdd.value = false
  show.value = true
}

const submit = async () => {
  try {
    isAdd.value ? await addAccident(form.value) : await updateAccident(form.value.recordId, form.value)
    show.value = false
    ElMessage.success(isAdd.value ? '安全事件记录成功' : '记录更新成功')
    load()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const del = async (id) => {
  try {
    await deleteAccident(id)
    ElMessage.success('记录删除成功')
    load()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

onMounted(async () => {
  if (role === 'caregiver') {
    elders.value = (await getEldersByCaregiver(userInfo.caregiverId)).data
  }
  await load()
})
</script>

<style scoped>
.accident-management {
  padding: 20px;
  background: linear-gradient(135deg, #fffde7 0%, #f5f7fa 100%);
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  animation: fadeInDown 0.8s ease-out;
}

.page-header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 600;
}

.page-description {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0;
  font-style: italic;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  animation: slideInUp 0.6s ease-out;
}

.filter-item {
  width: 100%;
}

.add-button {
  background: linear-gradient(45deg, #e74c3c, #c0392b);
  border: none;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.add-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(231, 76, 60, 0.3);
}

.accident-table {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.8s ease-out;
}

.description-text {
  line-height: 1.5;
  color: #2c3e50;
}

.severity-tag {
  font-weight: 500;
  border-radius: 12px;
  padding: 4px 12px;
}

:deep(.el-table th) {
  background: linear-gradient(135deg, #e74c3c, #c0392b);
  color: white;
  font-weight: 600;
}

:deep(.el-table tr:hover) {
  background-color: #fdf2f2;
  transition: background-color 0.3s ease;
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
